package cn.hxth.dubbo.service.impl;

import cn.hxth.api.model.Consumer;
import cn.hxth.api.query.ConsumerQueryObject;
import cn.hxth.api.query.PageResult;
import cn.hxth.api.service.IConsumerService;
import cn.hxth.api.util.SplitUtil;
import cn.hxth.dubbo.service.mapper.ConsumerMapper;
import cn.hxth.dubbo.service.mq.RabbitMQSender;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@Service
@Transactional
public class ConsumerServiceImpl implements IConsumerService {
    @Resource
    private ConsumerMapper consumerMapper ;
    @Autowired
    private RabbitMQSender rabbitMQSender;
    @Resource(name = "myRedisTemplate")
    private RedisTemplate<String,Object> redisTemplate ;
    @Override
    public boolean insertConsumer(Consumer consumer) {

       boolean flag = this.consumerMapper.insert(consumer) ;
       if(flag){
          this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"add\", \"data_type\": \"consumer\", \"cid\": " + consumer.getCid() +   "}");
       }
       return  flag ;
    }

    @Override
    public boolean updateConsumer(Consumer consumer) {
        boolean flag =  this.consumerMapper.updateByPrimaryKey(consumer) ;
        if(flag){
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"update\", \"data_type\": \"consumer\", \"cid\": " + consumer.getCid() +   "}");
        }
        return  flag ;
    }

    @Override
    public boolean removeConsumer(Integer cid) {

        boolean flag =  this.consumerMapper.deleteByPrimaryKey(cid);
        if (flag){
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"update\", \"data_type\": \"consumer\", \"cid\": " + cid +   "}");
        }
        return  flag ;
    }

    @Override
    public Consumer getConsumer(Integer cid) {
          String jsonStr = (String) this.redisTemplate.opsForValue().get("consumer_"+cid);
        System.out.println(jsonStr);
          if("".equals(jsonStr)||jsonStr==null){

              Consumer consumer = this.consumerMapper.selectByPrimaryKey(cid);
              this.redisTemplate.opsForValue().set("consumer_"+cid,JSONObject.toJSONString(consumer));
              return  consumer ;
          }
        return JSONObject.parseObject(jsonStr,Consumer.class) ;

    }



    @Override
    public PageResult findAll(ConsumerQueryObject consumerQueryObject) {
        Set<String> keys = null ;
        Integer count = this.consumerMapper.selectForCount(consumerQueryObject);
        // 如果购货单位查询的排序规则是以消费金额排序
        if(consumerQueryObject.getSortFlag()==1){
            // 从缓存中获取所有购货单位信息的key
            keys = this.redisTemplate.keys("consumer_*") ;}
            // 如果购货单位所要查询的实际数量匹配则查询缓存
            if(keys.size()==count){
            List<Object> allData = this.redisTemplate.opsForValue().multiGet(keys) ;
            // System.out.println(allData.get(0));
                JSONArray jsonArray = JSONArray.parseArray(JSONArray.toJSONString(allData));
                // System.out.println(JSONObject.parseObject(jsonArray.getJSONObject(0).toJSONString(),Consumer.class).getTitle()); ;
                // 将查询的来的结果分页
                List<Object> listData = SplitUtil.splitList(allData, consumerQueryObject.getCurrentPage(),consumerQueryObject.getPageSize()) ;
           return new PageResult(listData,allData.size(),consumerQueryObject.getCurrentPage(),consumerQueryObject.getPageSize()) ;
        }
        else{
        // 从数据库里取得购货单位数据
        List<Consumer> listData = this.consumerMapper.selectAll(consumerQueryObject);
        for(Consumer consumer:listData){
            // 将数据存入缓存(貌似应该用双写一致性。。。。。)
            this.redisTemplate.opsForValue().set("consumer_"+consumer.getCid(),JSONObject.toJSONString(consumer));
        }
        return  new PageResult(listData,count,consumerQueryObject.getCurrentPage(),consumerQueryObject.getPageSize()) ;
    }}

    @Override
    public boolean updateTotal(Consumer consumer) {
        // 更新购货单位总消费金额
        boolean flag = this.consumerMapper.updateTotal(consumer) ;
        if(flag){
            // 发送一条更新购货单位消息
            this.rabbitMQSender.send("data-change-queue","{\"event_type\": \"update\", \"data_type\": \"consumer\", \"cid\": " + consumer.getCid() +   "}");
        }
        return flag;
    }

    @Override
    public Consumer getConsumerForMq(Integer cid) {
        // 在发送更新mq之后从数据里查找最新数据
        Consumer consumer = this.consumerMapper.selectByPrimaryKey(cid);
        return  consumer ;
    }
}
